package copyengine.dataLayer.rpc
{
	import flash.utils.getTimer;

	import copyengine.utils.debug.CELog;
	import copyengine.utils.tick.GlobalTick;

	public final class CERpcCompressManger
	{
		private static var _instance:CERpcCompressManger;

		public static function get instance():CERpcCompressManger
		{
			if (_instance == null)
			{
				_instance=new CERpcCompressManger();
			}
			return _instance;
		}

		private var rpcManger:ICERpcManger;

		private var rpcRequestPool:Array;

		private var rpcRemainTick:int;

		private var isDuringSendingState:Boolean=false;

		public function CERpcCompressManger()
		{
		}

		public function initialize(_rpcManger:ICERpcManger):void
		{
			rpcManger=_rpcManger;
			rpcRequestPool=[];
			rpcRemainTick=CERpcConfig.RPC_TIME_TICK_IDLE;
			addListener();
		}

		private function addListener():void
		{
			GlobalTick.instance.callLaterAfterTimerCount(onTimeTick, 1, int.MAX_VALUE);
		}

		public function addRpcRequest(_request:Object, _rpcType:int):void
		{
			rpcRequestPool.push(_request);
			switch (_rpcType)
			{
				case CERpcConfig.RPC_TYPE_IMMEDIATELY:
					rpcRemainTick=0;
					break;
				case CERpcConfig.RPC_TYPE_SHORT_BUFFER:
					rpcRemainTick=CERpcConfig.RPC_TIME_TICK_SHOT_BUFFER;
					break;
				case CERpcConfig.RPC_TYPE_PASSIVITY_PUSH:
					break;
			}
			tryToSendRpcRequest();
		}

		/**
		 *强制将积攒的请求发送到服务器
		 * isIgnoreDuringSendState 是否忽略isDuringSendingState变量
		 *  只有在出错后最后发送错误errormsg时候才会忽略掉，因为error有可能是在DQ处理函数中产生
		 *  此时还没有调用onRpcRequestSendSucceed函数，则该变量不会设置为false
		 */
		public function flushRcpRequest(_isIgnoreDuringSendState:Boolean=false):void
		{
			if (_isIgnoreDuringSendState)
			{
				doSendRpcRequest();
			}
			else
			{
				rpcRemainTick=0;
				tryToSendRpcRequest();
			}
		}

		private function onTimeTick():void
		{
			rpcRemainTick--;
			tryToSendRpcRequest();
		}

		private function tryToSendRpcRequest():void
		{
			if (rpcRemainTick <= 0)
			{
				rpcRemainTick=CERpcConfig.RPC_TIME_TICK_IDLE;
				if (rpcRequestPool.length > 0)
				{
					sendRpcRequest();
				}
			}
		}

		private function sendRpcRequest():void
		{
			if (!isDuringSendingState)
			{
				isDuringSendingState=true;
				GlobalTick.instance.callLaterAfterTickCount(doSendRpcRequest);
			}
		}

		private function doSendRpcRequest():void
		{
			CELog.log("" + getTimer() + "  -------->Start Send Rcp , Total batch : " + rpcRequestPool.length);
			rpcManger.sendRequest(rpcRequestPool, onRpcRequestSendSucceed);
			rpcRequestPool=[];
			CELog.log("-------------------------------");
		}

		private function onRpcRequestSendSucceed():void
		{
			CELog.log("" + getTimer() + "Receive Rpc Request，--------> Remain batch :  " + rpcRequestPool.length);
			isDuringSendingState=false;
			flushRcpRequest();
		}

	}
}
